package com.atguigu.tingshu.album.mq;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.vo.album.CanalListenAlbumStatMsgVo;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import io.swagger.v3.core.util.Json;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Author  王东剑
 * Created on 17/6/2024 PM7:26
 * Package_name com.atguigu.tingshu.album.mq
 * Description
 */
@Component
public class TrackReceiver {
	@Autowired
	private AlbumInfoService albumInfoService;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
	public void updateStat(ConsumerRecord<String,String> record){
		String value = record.value();
		if(!StringUtils.isEmpty(value)){
			TrackStatMqVo trackStatMqVo = JSON.parseObject(value, TrackStatMqVo.class);
			String redisKey = RedisConstant.ALBUM_TRACK_BUSINESS_NO + trackStatMqVo.getBusinessNo();
			Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, JSON.toJSONString(trackStatMqVo), 1, TimeUnit.HOURS);
			if(ifAbsent){
				albumInfoService.updateAlbumTrackStat(trackStatMqVo);
			}

		}
	}


}
